from datetime import datetime

from flask_sqlalchemy import get_debug_queries
from log import logger


def sql_debug(response):
    """sql debug logger format sql"""

    try:
        queries = list(get_debug_queries())
        query_str = ''
        total_duration = 0.0
        flag = 1 if len(queries) > 0 else 0
        for q in queries:
            total_duration += q.duration
            parameters = {k: handle_sql_format(q.parameters.get(k)) for k in q.parameters}
            stmt = str(q.statement % parameters).replace('\n', '\n       ')
            query_str += '\n\nQuery: {0}\nDuration: {1}ms\n'.format(stmt, round(q.duration * 1000, 2))

        # 存在sql query 时 才输出
        if flag == 1:
            front_separator = '\n START' + '-' * 80
            end_separator = '\n END' + '-' * 80
            logger.warning(front_separator + query_str.rstrip('\n') + end_separator)
    # TODO here is not an Exception
    except Exception:
        logger.exception("特殊sql:无法解析")
    return response


def handle_sql_format(param):
    """sql format"""

    try:
        param = int(param)
    except ValueError:
        try:
            param = datetime.strptime(param, '%Y-%m-%d %H:%M:%S.%f+08:00')
        except ValueError:
            pass
        if isinstance(param, datetime):
            param = param.strftime('%Y-%m-%d %H:%M:%S')
        return "'{}'".format(param)
    return param
